
#!/usr/bin/env python3
"""
DeepSeekOCR-ESG测试系统验证脚本
用于验证平台功能是否正常
"""

import requests
import json
import os
import sys
from pathlib import Path

def test_api_health():
    """测试API健康状态"""
    try:
        response = requests.get("http://localhost:8000/")
        if response.status_code == 200:
            print("✅ API服务正常运行")
            return True
        else:
            print(f"❌ API服务异常: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 无法连接API服务: {e}")
        return False

def create_test_files():
    """创建测试文件"""
    # 创建一个简单的测试图片
    from PIL import Image, ImageDraw, ImageFont
    
    # 创建测试图片
    img = Image.new('RGB', (800, 600), color='white')
    draw = ImageDraw.Draw(img)
    
    # 添加测试文字
    text = """ESG报告测试
碳排放总量：1,250,000吨
员工人数：15,000人
能源消耗：2,100,000兆瓦时
"""
    
    try:
        font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 24)
    except:
        font = ImageFont.load_default()
    
    draw.text((50, 50), text, fill='black', font=font)
    
    # 保存测试文件
    test_dir = Path("test_files")
    test_dir.mkdir(exist_ok=True)
    
    img.save(test_dir / "test_esg.png")
    
    # 创建对应的标注文件
    with open(test_dir / "test_ground_truth.txt", "w", encoding="utf-8") as f:
        f.write(text)
    
    print("✅ 测试文件创建完成")
    return test_dir

def run_test():
    """运行完整测试"""
    print("🧪 开始DeepSeekOCR-ESG测试平台验证...")
    print("=" * 50)
    
    # 1. 测试API
    if not test_api_health():
        sys.exit(1)
    
    # 2. 创建测试文件
    test_dir = create_test_files()
    
    # 3. 上传测试文件
    print("📤 上传测试文件...")
    try:
        with open(test_dir / "test_esg.png", "rb") as f:
            files = {"file": f}
            response = requests.post("http://localhost:8000/api/upload-report", files=files)
        
        if response.status_code == 200:
            result = response.json()
            report_id = result["report_id"]
            print(f"✅ 文件上传成功，报告ID: {report_id}")
        else:
            print(f"❌ 文件上传失败: {response.text}")
            return
    except Exception as e:
        print(f"❌ 文件上传异常: {e}")
        return
    
    # 4. 执行OCR
    print("🔍 执行OCR识别...")
    try:
        data = {"report_id": report_id}
        response = requests.post("http://localhost:8000/api/perform-ocr", data=data)
        
        if response.status_code == 200:
            ocr_result = response.json()
            print("✅ OCR识别完成")
            print(f"   处理页数: {len(ocr_result['results'])}")
            print(f"   总耗时: {ocr_result['total_processing_time']:.2f}秒")
        else:
            print(f"❌ OCR识别失败: {response.text}")
            return
    except Exception as e:
        print(f"❌ OCR识别异常: {e}")
        return
    
    # 5. 上传标准答案
    print("📝 上传标准答案...")
    try:
        with open(test_dir / "test_ground_truth.txt", "rb") as f:
            files = {"ground_truth": f}
            data = {"report_id": report_id}
            response = requests.post(
                "http://localhost:8000/api/upload-ground-truth", 
                data=data, 
                files=files
            )
        
        if response.status_code == 200:
            print("✅ 标准答案上传成功")
        else:
            print(f"❌ 标准答案上传失败: {response.text}")
            return
    except Exception as e:
        print(f"❌ 标准答案上传异常: {e}")
        return
    
    # 6. 计算准确率
    print("📊 计算准确率...")
    try:
        data = {"report_id": report_id}
        response = requests.post("http://localhost:8000/api/calculate-accuracy", data=data)
        
        if response.status_code == 200:
            accuracy_result = response.json()
            print("✅ 准确率计算完成")
            print("📈 测试结果:")
            print(f"   字符级准确率: {accuracy_result['overall_accuracy']['character_accuracy']*100:.1f}%")
            print(f"   段落级准确率: {accuracy_result['overall_accuracy']['paragraph_accuracy']*100:.1f}%")
            print(f"   关键字段召回率: {accuracy_result['overall_accuracy']['field_recall']*100:.1f}%")
            
            # 保存结果
            with open(f"test_report_{report_id}.json", "w", encoding="utf-8") as f:
                json.dump(accuracy_result, f, ensure_ascii=False, indent=2)
            print(f"📄 测试报告已保存: test_report_{report_id}.json")
        else:
            print(f"❌ 准确率计算失败: {response.text}")
    except Exception as e:
        print(f"❌ 准确率计算异常: {e}")

if __name__ == "__main__":
    print("DeepSeekOCR-ESG测试平台验证工具")
    print("请确保后端服务已启动: python backend/main.py")
    print()
    
    input("按Enter键开始测试...")
    run_test()
